library(ggplot2)
library(reshape2)

# Create data frame with values as proportions
df <- data.frame(
  Party = c("Total", "Democrat", "D. Lean", "Republican", "R. Lean", "Other"),
  `Strongly agree` = c(.203, .283, .222, .056, .049, .256),
  Agree = c(.427, .516, .472, .274, .243, .307),
  `Neither agree nor disagree` = c(.171, .134, .172, .207, .273, .190),
  Disagree = c(.106, .047, .096, .217, .209, .088),
  `Strongly disagree` = c(.092, .021, .037, .246, .226, .161),
  check.names = FALSE
)

# Sort the data by 'Strongly disagree' values in descending order
df <- df[order(-df$`Strongly disagree`),]

# Update the Party factor levels based on the sorted order
df$Party <- factor(df$Party, levels = df$Party)

# Melt the data for use with ggplot, specify variable.name to avoid automatic conversion of spaces to dots
data_long <- melt(df, id.vars = "Party", variable.name = "Response")

# Function to format labels as whole numbers
format_label <- function(value) {
  percentage <- round(value * 100)
  return(as.character(percentage))
}

# Map custom colors to response levels
custom_colors <- c(`Strongly agree` = "blue", `Agree` = "lightblue", 
                   `Neither agree nor disagree` = "white", `Disagree` = "orange", 
                   `Strongly disagree` = "red")

# Create the stacked bar plot with a black border around the bars and add text labels formatted as whole numbers
ggplot(data_long, aes(x = Party, y = value, fill = Response, label = sapply(value, format_label))) +
  geom_bar(stat = "identity", position = "stack", colour = "black") +
  geom_text(position = position_stack(vjust = 0.5), color = "black", size = 3) +
  scale_fill_manual(values = custom_colors, labels = c("Strongly Agree", "Agree", "Neither Agree nor Disagree", "Disagree", "Strongly Disagree")) +
  scale_y_continuous(labels = scales::percent_format()) +
  coord_flip() +  # Flip coordinates to have parties on the y-axis
  labs(y = "", x = "", fill = "", 
       title = "Support for US Climate Aid to Poor Countries") +
  theme_minimal() +  # Use a minimal theme
  theme(panel.grid.major.y = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "gray"),
        legend.position = "bottom")  # Adjust legend position

# Save the plot
ggsave("MessagingFigsR/climate_aid_support.png", width = 10, height = 6, dpi = 300)
